#!/usr/bin/env bash

# Copyright (C) Lightbend Inc. <https://www.lightbend.com>

# Lib for CI scripts

set -e
set -o pipefail

DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
BASEDIR=$DIR/..
export DOCUMENTATION=$BASEDIR/documentation

export CURRENT_BRANCH=${TRAVIS_BRANCH}

AKKA_VERSION=""
AKKA_HTTP_VERSION=""

# Check if it is a scheduled build
if [ "$TRAVIS_EVENT_TYPE" = "cron" ]; then
  if [ -f $HOME/.ivy2/local/com.typesafe.play/AKKA_VERSION ]; then
    AKKA_VERSION=$(cat $HOME/.ivy2/local/com.typesafe.play/AKKA_VERSION)
  else
    AKKA_VERSION=$(curl -s https://repo.akka.io/snapshots/com/typesafe/akka/akka-actor_2.13/ | grep -oEi '2\.6\.[0-9]+\+[0-9]+-[0-9a-f]{8}' | sort -V | tail -n 1)
  fi
  if [ -f $HOME/.ivy2/local/com.typesafe.play/AKKA_HTTP_VERSION ]; then
    AKKA_HTTP_VERSION=$(cat $HOME/.ivy2/local/com.typesafe.play/AKKA_HTTP_VERSION)
  else
    AKKA_HTTP_VERSION=$(curl -s https://dl.bintray.com/akka/snapshots/com/typesafe/akka/akka-http-core_2.13/maven-metadata.xml | xmllint --xpath '//latest/text()' -)
  fi

  echo "Using Akka SNAPSHOT ${AKKA_VERSION} and Akka HTTP SNAPSHOT ${AKKA_HTTP_VERSION}"

  AKKA_VERSION_OPTS="-Dakka.version=${AKKA_VERSION}"
  AKKA_HTTP_VERSION_OPTS="-Dakka.http.version=${AKKA_HTTP_VERSION}"
fi

printMessage() { echo -e "\033[33;1m[info] ---- $1\033[0m"; }
start() { echo -e "travis_fold:start:$1\033[33;1m[info] ---- $2\033[0m"   ; }
end()   { echo -e "\ntravis_fold:end:$1\r\033[32;1m[info] ---- $2\033[0m" ; }

runSbt() {
  sbt "$AKKA_VERSION_OPTS" "$AKKA_HTTP_VERSION_OPTS" -jvm-opts "$BASEDIR/.travis-jvmopts" 'set concurrentRestrictions in Global += Tags.limitAll(1)' "$@" | grep --line-buffered -v 'Resolving \|Generating '
}

# Runs code formating validation in the current directory
scalafmtValidation() {
  start validate-scalafmt "VALIDATE SCALA CODE FORMATTING"
  runSbt +scalafmtCheckAll scalafmtSbtCheck || (
    echo "[error] ERROR: Scalafmt test failed for $1 source."
    echo "[error] To fix, format your sources using 'sbt scalafmtAll scalafmtSbt' before submitting a pull request."
    false
  )
  ret=$?
  end validate-scalafmt "VALIDATED SCALA CODE FORMATTING"
  return $ret
}

# Runs code formating validation in the current directory
javafmtValidation() {
  start validate-javafmt "VALIDATE JAVA CODE FORMATTING"
  runSbt javafmtCheckAll || (
    echo "[error] ERROR: javafmt check failed for $1 source."
    echo "[error] To fix, format your sources using 'sbt javafmtAll' before submitting a pull request."
    false
  )
  ret=$?
  end validate-javafmt "VALIDATE JAVA CODE FORMATTING"
  return $ret
}
